
package com.sunwayhorizo.health.hl7.persistent;

import com.sunwayhorizo.health.hl7.common.DataTypeUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.datatypes.CD;
import com.sunwayhorizo.health.hl7.datatypes.CS;
import com.sunwayhorizo.health.hl7.factories.ReferenceModifier;

import java.io.Serializable;

import java.sql.Timestamp;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

/**
 * @ClassName InfrastructureRoot <br>
 * @PackageName com.sunwayhorizo.health.hl7.persistent <br>
 * @Description 
 *     这个类为一个超类，所有的类都继承与它。 <br>
 *     此类提供了所有派生类适用的属性和方法。 <br> *     
 * @Author xuyx <br>
 * @Date 2010-03-07 <br>
 * @Version 1.0 <br>
 * @ModifiedDesc <br>
 * @ModifiedDate <br>
 * @ModifiedBy jinzw<br>
 * @Copyright 2010-2020  All Rights Reserved. <br>
 */
@MappedSuperclass
//@TableGenerator(name = "IdGenerator", table = "Rim_Id_Generator", pkColumnName = "pkColumn", valueColumnName = "valueColumn",pkColumnValue = "Core_Id")
//@IdClass(RimCorePK.class)
public class InfrastructureRoot
    implements Serializable
{
/*    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "IdGenerator")
    private Long systemId ;
    @Id
    private Long versionNum ;
*/    
	/**
	 * 适用于所有派生类的属性，每一个实体，角色，动作都有一个classCode来区分。
	 * 元素定义遵循Hl7标准，可以理解为大类
	 */
    @Column(name = "CLASS_CODE", nullable = false)    
    private String classCode;
    
    /**
     * 当前版本标记
     */
    @Column(name = "CURRENT_VERSION_FLAG")    
    private String currentVersionFlag;
    
    /**
     * 在classCode大类下进一步细分的亚类
     */
    private String codeEtsId;
    
    /**
     * 状态code，标记一个对象当前状态值
     */
    @Column(name = "STATUS_CODE")    
    private String statusCode;

    /**
     * 当前版本开始时间
     */
    @Column(name = "VERSION_START_DATE_TS", nullable = false)    
    private Timestamp versionStartDateTs;
    
    /**
     * 当前版本结束时间
     */
    @Column(name = "VERSION_END_DATE_TS", nullable = false)    
    private Timestamp versionEndDateTs;
    
    /**
     * 创建人
     */
    @Column(name = "CREATED_BY", nullable = false)    
    private Long createdBy;  
    
    /**
     * 创建时间
     */
    @Column(name = "CREATION_DATE", nullable = false)    
    private Timestamp creationDate ; 
    
    /**
     * 最后修改人
     */
    @Column(name = "LAST_UPDATED_BY", nullable = false)    
    private Long lastUpdatedBy ; 
    
    /**
     * 最后修改时间
     */
    @Column(name = "LAST_UPDATE_DATE", nullable = false)    
    private Timestamp lastUpdateDate  ; 
    
     /**
      * 最后登录人记载
      */
    @Column(name = "LAST_UPDATE_LOGIN")   
    private Long lastUpdateLogin;
    
    /**
     * 是否被查询
     */
    @Transient boolean isQueried;
    /**
     * 是否被删除
     */
    @Transient boolean isRemoved;
    /**
     * 是否为完成的对象
     */
    @Transient boolean isCompleteObject;
    /**
     * 是否是伪标记
     */
    @Transient boolean isPseudo;
    
    /**
     * 引用类型
     */
    @Transient ReferenceModifier referenceType;
        
    //    @ManyToOne
    //    @JoinColumn(name = "MASTER_CATALOG_ID",referencedColumnName = "MASTER_CATALOG_ID")
    //    private McEntries mcEntries;
    //    @Column(name = "MASTER_CATALOG_ID", nullable = false)    private Long masterCatalogId = new Long(1);

    
    /**
     * 与RimCoreActs为多对一的关系，
     */
    @ManyToOne
    @JoinColumns( { @JoinColumn(name = "CNTRL_ACT_ID",  referencedColumnName = "ACT_ID") , 
                    @JoinColumn(name = "CNTRL_ACT_VERSION_NUM", referencedColumnName =  "ACT_VERSION_NUM")
                    } )
    private RimCoreActs controlAct;

    public InfrastructureRoot()
    {
        Long i = new Long(1);
        Timestamp nowTime = new Timestamp(new Date().getTime());
        
//        versionNum = i;
        
        currentVersionFlag = new String("Y");        
        versionStartDateTs = nowTime ; 
        versionEndDateTs = nowTime ;             
        createdBy = i;
        creationDate = nowTime ;
        lastUpdatedBy = i;
        lastUpdateDate = nowTime;   
        lastUpdateLogin = i;        
        
        isQueried = false;
        isRemoved = false;
        isCompleteObject = false;
        isPseudo = false;
        referenceType = null;

    }

    public InfrastructureRoot(ReferenceModifier referencemodifier)
    {
/*        isQueried = false;
        isRemoved = false;
        isCompleteObject = false;
        isPseudo = false;
*/
        referenceType = referencemodifier;
    }
/*
    public String[] getAllAttributeNames()
    {
        return valueAttributes;
    }

    public Object getQueryPrefetchValue(CoreFetch corefetch, String s)
    {
        Object obj = null;
        FetchKey fetchkey = new FetchKey(corefetch, s);
        if(mPrefetch != null && mPrefetch.containsKey(fetchkey))
            obj = mPrefetch.get(fetchkey);
        return obj;
    }

    public void setQueryPrefetchValue(CoreFetch corefetch, String s, Object obj)
    {
        FetchKey fetchkey = new FetchKey(corefetch, s);
        if(mPrefetch == null)
            mPrefetch = new HashMap(5);
        mPrefetch.put(fetchkey, obj);
    }
*/
    /**
     * 设置Entity、Role、Act的分类
     * @param CS classCode  大类分类
     * @return
     * @throws Hl7Exception
     */    
    public void setClassCode(CS classCode) {
        this.setClassCode(classCode.toString());
    }
  /**
   * 获得Entity、Role、Act的分类
   * @return CS classCode 大类分类
   * @throws Hl7Exception
   */
    public CS getClassCode() throws Hl7Exception {
        return DataTypeUtil.getCS(this.getClass_Code());
    }
  /**
   * 设置Entity、Role、Act分类下的亚类
   * @param CD code 亚类分类
   * @return
   * @throws Hl7Exception
   */        
    public void setCode(CD code) {
    	if(null == code){
    		return;
    	}
        this.setCodeEtsId(code.code().toString());
    }
  /**
   * 获得Entity、Role、Act分类的亚类
   * @return CS classCode 亚类分类
   * @throws Hl7Exception
   */
    public CD getCode() throws Hl7Exception {
    	if("<Null:NullFlavor: NI>".equals(getCodeEtsId())) return null; //如果没有EtsId返回null
        return DataTypeUtil.getCE(this.getCodeEtsId());
    }
    
    public void setStatusCode(CS statusCode) {
        this.setStatusCode(statusCode.code().toString());
    }

    public CS getStatusCode() throws Hl7Exception {
     return DataTypeUtil.getCS(this.getStatus_Code());
    }
    
    
/*    private void setsystemId(Long id) {
        this.systemId = id;
    }

    private Long getsystemId() {
        return systemId;
    }

    private void setVersionNum(Long versionNum) {
        this.versionNum = versionNum;
    }

    private Long getVersionNum() {
        return versionNum;
    }
*/    
    protected String getClass_Code() {
        return classCode;
    }   

    protected void setClassCode(String classCode) {
        this.classCode = classCode;
    }


    protected String getCurrentVersionFlag() {
        return currentVersionFlag;
    }

    protected void setCurrentVersionFlag(String currentVersionFlag) {
        this.currentVersionFlag = currentVersionFlag;
    }

    private void setCodeEtsId(String codeEtsId) {
        this.codeEtsId = codeEtsId;
    }

    protected String getCodeEtsId() {
        return codeEtsId;
    }

    private void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    private String getStatus_Code() {
        return statusCode;
    }
    
     protected Timestamp getVersionStartDateTs() {
         return versionStartDateTs;
     }

     protected void setVersionStartDateTs(Timestamp versionStartDateTs) {
         this.versionStartDateTs = versionStartDateTs;
     }
     
     protected Timestamp getVersionEndDateTs() {
         return versionEndDateTs;
     }

     protected void setVersionEndDateTs(Timestamp versionEndDateTs) {
         this.versionEndDateTs = versionEndDateTs;
     }
     
    public Long getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Long createdBy) {
        this.createdBy = createdBy;
    }
    
    public Timestamp getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Timestamp creationDate) {
        this.creationDate = creationDate;
    }
    
    public Long getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(Long lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

    public Timestamp getLastUpdateDate() {
        return lastUpdateDate;
    }

    public void setLastUpdateDate(Timestamp lastUpdateDate) {
        this.lastUpdateDate = lastUpdateDate;
    }

    protected Long getLastUpdateLogin() {
        return lastUpdateLogin;
    }

    protected void setLastUpdateLogin(Long lastUpdateLogin) {
        this.lastUpdateLogin = lastUpdateLogin;
    }

    public boolean isQueried()
    {
        return isQueried;
    }

    public void setQueried(boolean flag)
    {
        isQueried = flag;
    }

    public ReferenceModifier getReferenceType()
    {
        return referenceType;
    }

    public void setReferenceType(ReferenceModifier referencemodifier)
    {
        referenceType = referencemodifier;
    }

    public boolean isRemoved()
    {
        return isRemoved;
    }

    public void setRemoved(boolean flag)
    {
        isRemoved = flag;
    }

    public boolean isCompleteObject()
    {
        return isCompleteObject;
    }

    public void setCompleteObject(boolean flag)
    {
        isCompleteObject = flag;
    }

    public boolean isPseudo()
    {
        return isPseudo;
    }

    public void setPseudo(boolean flag)
    {
        isPseudo = flag;
    }
   
    
    public void setControlAct(RimCoreActs controlAct) {
        this.controlAct = controlAct;
    }

    public RimCoreActs getControlAct() {
        return controlAct;
    }

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((classCode == null) ? 0 : classCode.hashCode());
		result = prime * result
				+ ((codeEtsId == null) ? 0 : codeEtsId.hashCode());
		result = prime * result
				+ ((statusCode == null) ? 0 : statusCode.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		InfrastructureRoot other = (InfrastructureRoot) obj;
		if (classCode == null) {
			if (other.classCode != null)
				return false;
		} else if (!classCode.equals(other.classCode))
			return false;
		if (codeEtsId == null) {
			if (other.codeEtsId != null)
				return false;
		} else if (!codeEtsId.equals(other.codeEtsId))
			return false;
		if (statusCode == null) {
			if (other.statusCode != null)
				return false;
		} else if (!statusCode.equals(other.statusCode))
			return false;
		return true;
	}


/*    protected void copyQueryAttributes(HashMap hashmap, InfrastructureRoot infrastructurerootimpl)
    {
        if(hashmap != null)
        {
            Set set = hashmap.keySet();
            for(Iterator iterator = set.iterator(); iterator.hasNext();)
            {
                FetchKey fetchkey = (FetchKey)iterator.next();
                String s = fetchkey.getImplConstant();
                Object obj = hashmap.get(fetchkey);
                if(obj != null && (obj instanceof Collection))
                    infrastructurerootimpl.setOriginalAttribute(s, obj);
                else
                if(obj != null && ((InfrastructureRoot)obj).isCurrentVersion())
                    infrastructurerootimpl.setOriginalAttribute(s, obj);
            }

        }
    }

    public ControlAct getControlAct()
        throws CTBException
    {
        ControlAct controlact = null;
        int i = 0;
        if(isQueried())
        {
            HashMap hashmap = getAllQueryPrefetchValues();
            if(hashmap != null && hashmap.keySet() != null)
            {
                for(Iterator iterator = hashmap.keySet().iterator(); iterator != null && iterator.hasNext();)
                {
                    FetchKey fetchkey = (FetchKey)iterator.next();
                    String s = fetchkey.getImplConstant();
                    if(s.equals("ControlAct"))
                    {
                        i++;
                        controlact = (ControlAct)hashmap.get(fetchkey);
                    }
                }

            }
        } else
        {
            controlact = (ControlAct)getAttribute("ControlAct");
        }
        if(i > 1)
            throw newMultipleValueFoundException("getControlAct");
        else
            return controlact;
    }

    protected Hl7Exception newMethodException(String s, String s1)
    {
        String as[] = {
            "METHOD_NAME", "OBJECT_TYPE"
        };
        String as1[] = {
            s
        };
        String s2 = MessageUtils.getMessage("Attempt to call unsupported method on the supplied object.\n\nMethod Name: &METHOD_NAME", as, as1);
        return new RimObjectException(null, as1, "CTB_CORE_METHOD_NOT_ALLOWED", s2, null);
    }

    protected Hl7Exception newParameterMissingException(String s)
    {
        String as[] = {
            "PARAM1"
        };
        String as1[] = {
            s
        };
        String s1 = MessageUtils.getMessage("Invalid parameter was passed into this API. Required parameter [&PARAM1] was null.", as, as1);
        return new RimAttributeMissingException(as1, "CTB_NULL_PARAMETER", s1, s);
    }

    protected Hl7Exception newMultipleValueFoundException(String s)
    {
        String as[] = {
            "METHOD_NAME"
        };
        String as1[] = {
            s
        };
        String s1 = MessageUtils.getMessage("More than one result returned for attribute of cardinality 1.\n\nMethod Name: &METHOD_NAME", as, as1);
        return new RimObjectException(null, as1, "CTB_CORE_MULTIPLE_RETURN_VALUE", s1, null);
    }

    protected static RuntimeException newQueryAttributeMissingException(String s)
    {
        String as[] = {
            "PARAM1"
        };
        String as1[] = {
            s
        };
        String s1 = MessageUtils.getMessage("The requested attribute was notretrieved.\n\nParameter Name: [&PARAM1]", as, as1);
        return new RuntimeException(s1);
    }
 */   
    
}
